<?php

namespace App\Store\Controllers\OldMaterial;

use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\OldMaterial\Allot;
use App\Store\Models\OldMaterial\AllotInfolist;
use App\Store\Models\OldMaterial\Log;
use App\Store\Models\OldMaterial\Stock;
use App\Store\Services\Goods\Goods;
use App\Store\Services\Goods\GoodsAllotService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Validate\OldMaterial\Allot as ValidateOldMaterialAllot;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 调拨，门店之间调拨
 */
class AllotController extends Controller
{
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['target_store_id', 'remark', 'oldmaterial_list']);
        $Validate = new ValidateOldMaterialAllot();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $start_store_id = $accountinfo['store_ids'];

        //处理调拨旧料列表
        $oldmaterial_list = $req_data['oldmaterial_list'];
        $oldmaterial_info_data = is_array($oldmaterial_list) ? $oldmaterial_list : (is_array(json_decode($oldmaterial_list, true)) ? json_decode($oldmaterial_list, true) : []);
        $goods_count = 0;
        foreach ($oldmaterial_info_data as &$v) {
            $goods_count += $v['count'];
            $v['goods_category_id'] = $v['goods_category']['id'];
        }

        $checkData = (new  GoodsAllotService())->checkAllotGoods($cp_id, $req_data['target_store_id'], $oldmaterial_info_data, $accountinfo);
        if (!empty($checkData['err_msg']) || empty($checkData['data'])) {
            return response()->json(['code' => '001', 'msg' => '商品数据调拨失败,' . implode(',', $checkData['err_msg'])]);
        }


        $oldAllotArr = $checkData['data'] ?? [];
        DB::beginTransaction();
        try {
            $order_sncode = StoreCommon::createOrderSn();
            $oldmaterial_data = [
                'cp_id' => $cp_id,
                'start_store_id' => $start_store_id,
                'target_store_id' => $req_data['target_store_id'],
                'order_sncode' => $order_sncode,
                'goods_count' => $goods_count,
                'remark' => $req_data['remark'],
                'create_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'create_at' => time(),
            ];

            //调拨单
            $oldmaterial_id = Allot::query()->create($oldmaterial_data)->id;

            //调拨明细
            $stockIds = array_column($oldAllotArr, 'id');
            $stockList = Stock::query()
                ->where(['cp_id' => $cp_id, 'store_id' => $start_store_id])
                ->whereIn('id', $stockIds)
                ->get()
                ->pluck(null, 'id')
                ->toArray();


            $allotArr=[];
            $log=[];
            foreach ($oldAllotArr as  $v) {
                //旧料库存更新为调拨
                $stock = $stockList[$v['id']] ?? [];
                $arr = $this->checkBCstock($stock, $v, false,1);

                // 追加
                $v['audit_status'] = 1;
                $v['stock_id'] = $v['id'];
                $v['start_store_id'] = $start_store_id;
                $v['target_store_id'] = $req_data['target_store_id'];
                $v['order_sncode'] = $order_sncode;
                $v['cp_id'] = $cp_id;
                $v['p_id'] = $oldmaterial_id;
                $v['create_account_id'] = $accountinfo['id'];
                $v['create_account_real_name'] = $accountinfo['real_name'];
                $v['create_at'] = time();
                unset($v['id'], $v['goods_brand'], $v['goods_pricetype'], $v['goods_category'], $v['storeinfo'], $v['type']);


                //删除不需要的字段
                if (!empty($stock)) {
                    $stockData = $this->checkBCstock($stock, $v, false);
                    $stockData['stock_status'] = 2;
                    $stockData['update_at'] = time();

                    $v['total_cost_fee'] = $stockData['deduct_total_cost_fee'];
                    $stockData['total_cost_fee'] =$stockData['remaining_cost_fee'];
                    unset($stockData['deduct_total_cost_fee'], $stockData['remaining_cost_fee']);

                    Stock::query()->where('id',$v['stock_id'])->update($stockData);
                }
                $allotArr[] = array_merge($v,$arr);

                //日志
                $log[] =[
                    'cp_id' => $cp_id,
                    'store_id' => $v['store_id'],
                    'start_store_id' => $start_store_id,
                    'target_store_id' => $req_data['target_store_id'],
                    'order_sncode' => $order_sncode,
                    'goods_category_id' => $v['goods_category_id'],
                    'piece_weight' => $v['piece_weight'],
                    'stock_type' => $v['stock_type'],
                    'count' => $v['count'],
                    'cf_no' => $v['cf_no'],
                    'log_type' => 2,
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ];

            }

            Log::query()->insert($log);
            AllotInfolist::query()->insert($allotArr);


            DB::commit();
            return response()->json(['code' => '000', 'msg' => '添加成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getLine().$e->getMessage()]);
        }

    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $list = Allot::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        //不分页
        $request['isgetall'] = 1;
        $list = Allot::getList($request)['list'] ?? [];
        if ($list) {
//            $ids = [];
//            foreach ($list['list'] as $v) {
//                $ids[] = $v['id'];
//            }
//
//            $infolist = AllotInfolist::with('startstoreinfo', 'targetstoreinfo', 'goods_category', 'goods_brand')->whereIn('p_id', $ids)->get()->toArray();

            $row = [
                ['start_store' => '旧料调拨'],
                [
                    'start_store_name' => '起始门店',
                    'target_store_name' => '目的门店',
                    'order_sncode' => '调拨单号',
                    'audit_status' => '订单状态',
                    'goods_count' => '数量',
                    'create_account_real_name' => '创建人',
                    'create_at' => '创建时间'
                ]];
            $exceldata = [];
            foreach ($list as $val) {
                $exceldata[] = [
                    'start_store_name' => $val['startstoreinfo'] ? $val['startstoreinfo']['store_name'] : '',
                    'target_store_name' => $val['targetstoreinfo'] ? $val['targetstoreinfo']['store_name'] : '',
                    'order_sncode' => $val['order_sncode'],
                    'audit_status' => $val['audit_status'] == 1 ? '待审核' : ($val['audit_status'] == 2 ? '审核中' : '审核'),
                    'goods_count' => $val['goods_count'],
                    'create_account_real_name' => $val['create_account_real_name'],
                    'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                ];
            }

            $filename = '旧料调拨信息导出_' . time() . '.xlsx';
            return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
        }
        return response()->json(['code' => '001', 'msg' => '导出失败']);
    }

    /**
     * 详情
     */
    public function getinfolist(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = Allot::where(['id' => $id, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $where = [];
        $order_sncode = $request->order_sncode ?? '';
        if ($order_sncode != '') {
            $where[] = ['order_sncode', 'like', '%' . $order_sncode . '%'];
        }

        $goods_category_id = $request->goods_category_id ?? 0;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $audit_status = $request->audit_status ?? 0;

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $target_store_id = Allot::where(['id' => $id])->first()->target_store_id;
        if ($accountinfo['type'] != 1 || $accountinfo['store_ids'] != $target_store_id) {
            $info['audit'] = 2;
        } else {
            $info['audit'] = 1;
        }

        //按照类别汇总
        $list1_new = [];
        $list1 = AllotInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where)
            ->groupBy('goods_category_id')
            ->select('goods_category_id', DB::raw('sum(count) as count,sum(audit_success_count) as audit_success_count,sum(audit_failed_count) as audit_failed_count,sum(piece_weight) as piece_weight,sum(piece_weight_new) as piece_weight_new,sum(exchange_amount) as exchange_amount'))
            ->get()->toArray();

        if ($list1) {
            foreach ($list1 as $k => $v) {
                if ($v['audit_failed_count'] + $v['audit_success_count'] >= $v['count']) {
                    $status = 3;
                } elseif ($v['audit_failed_count'] + $v['audit_success_count'] < $v['count']) {
                    if ($v['audit_failed_count'] == 0 && $v['audit_success_count'] == 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                }
                $list1[$k]['audit_status'] = $status;

                if ($audit_status > 0) {
                    if ($status != $audit_status) {
                        unset($list1[$k]);
                    }
                }
            }
            $list1_new = array_values($list1);
        }

        //查询子订单详情
        $list2_query = AllotInfolist::with(['storeinfo', 'startstoreinfo', 'targetstoreinfo', 'goods_category', 'supply', 'goods_brand', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where);
        if ($audit_status > 0) {
            $list2_query->where('audit_status', $audit_status);
        }
        $list2 = $list2_query->get()->toArray();

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info, 'list1' => $list1_new, 'list2' => $list2]]);
    }

    /**
     * 汇总导出
     */
    public function dosummaryexport(Request $request)
    {
        $id = $request->id ?? 0;
        $ids = $request['ids'];
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = Allot::where(['id' => $id, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $where = [];
        $goods_category_id = $request->goods_category_id ?? 0;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $query = AllotInfolist::with(['goods_category'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where);

        if (count($ids) > 0) {
            $query->whereIn('goods_category_id', $ids);
        }

        $list = $query->groupBy('goods_category_id')
            ->select('goods_category_id', DB::raw('sum(count) as count,sum(piece_weight) as piece_weight,sum(piece_weight_new) as piece_weight_new,sum(exchange_amount) as exchange_amount'))
            ->get()->toArray();

        $row = [
            ['start_store' => '旧料类别汇总'],
            [
                'goods_category_id' => '旧料类别',
                'count' => '件数',
                'piece_weight' => '重量',
                'piece_weight_new' => '实重',
                'exchange_amount' => '换货金额',
            ]];

        $exceldata = [];
        foreach ($list as $val) {
            $exceldata[] = [
                'goods_category_id' => $val['goods_category']['category_name'] ?? '',
                'count' => $val['count'],
                'piece_weight' => $val['piece_weight'],
                'piece_weight_new' => $val['piece_weight_new'],
                'exchange_amount' => $val['exchange_amount'],
            ];
        }

        $filename = '旧料调拨汇总信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 明细导出
     */
    public function doinfolistexport(Request $request)
    {
        $id = $request->id ?? 0;
        $ids = $request['ids'];
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = Allot::where(['id' => $id, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $where = [];
        $goods_category_id = $request->goods_category_id ?? 0;
        if ($goods_category_id > 0) {
            $where[] = ['goods_category_id', $goods_category_id];
        }

        $query = AllotInfolist::with(['startstoreinfo', 'targetstoreinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info'])->where(['p_id' => $id, 'cp_id' => $cp_id])->where($where);

        if (count($ids) > 0) {
            $query->whereIn('id', $ids);
        }

        $list = $query->get()->toArray();

        $row = [
            ['start_store' => '旧料调拨明细'],
            [
                'start_store_name' => '起始门店',
                'target_store_name' => '目的门店',
                'order_sncode' => '订单号',
                'create_at' => '回收时间',
                'stock_type' => '回收方式',
                'goods_sn_code' => '条码',
                'goods_category_id' => '旧料类别',
                'count' => '数量',
                'piece_weight' => '重量',
                'piece_weight_new' => '实重',
                'cf_no' => '证书号',
                'goods_brand_id' => '品牌',
                'goods_pricetype_id' => '价格类型',
                'main_stone_weigth' => '主石重',
                'main_stone_count' => '主石数',
                'other_stone_weigth' => '副石重',
                'other_stone_count' => '副石数',
                'color' => '颜色',
                'clarity' => '净度',
                'exchange_amount' => '换货金额',
            ]];

        $exceldata = [];
        foreach ($list as $val) {
            $exceldata[] = [
                'start_store_name' => $val['startstoreinfo']['store_name'],
                'target_store_name' => $val['targetstoreinfo']['store_name'],
                'order_sncode' => $val['order_sncode'],
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'stock_type' => ($val['stock_type'] == 1) ? '按克' : '标价',
                'goods_sn_code' => $val['goods_sn_code'],
                'goods_category_id' => $val['goods_category']['category_name'] ?? '',
                'count' => $val['count'],
                'piece_weight' => $val['piece_weight'],
                'piece_weight_new' => $val['piece_weight_new'],
                'cf_no' => $val['cf_no'],
                'goods_brand_id' => $val['brand']['brand_name'] ?? '',
                'goods_pricetype_id' => '价格类型',
                'main_stone_weigth' => $val['main_stone_weigth'],
                'main_stone_count' => $val['main_stone_count'],
                'other_stone_weigth' => $val['other_stone_weigth'],
                'other_stone_count' => $val['other_stone_count'],
                'color' => $val['color'],
                'clarity' => $val['clarity'],
                'exchange_amount' => $val['exchange_amount'],
            ];
        }

        $filename = '旧料调拨明细信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 删除
     */
    public function dodel(Request $request)
    {
        $req_data = $request->only(['id']);
        $Validate = new ValidateOldMaterialAllot('del');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);

        DB::beginTransaction();
        try {

            $infolist = AllotInfolist::where('p_id', $req_data['id'])->get()->toArray();
            if (!empty($infolist)) {
                $stockIds = array_column($infolist, 'stock_id');
                $stockList = Stock::query()
                    ->where(['cp_id' => $cp_id])
                    ->whereIn('id', $stockIds)
                    ->get()
                    ->pluck(null, 'id')
                    ->toArray();

                foreach ($infolist as $v) {
                    $stock = $stockList[$v['stock_id']] ?? [];
                    // 待审核需要退回
                    if (!empty($stock) && $v['audit_status'] == 1) {

                        $stockData = $this->checkBCstock($stock, $v, true);
                        $stockData['stock_status'] = 1;
                        $stockData['update_at'] = time();
                        Stock::query()
                            ->where('id', $v['stock_id'])
                            ->where('cp_id', $cp_id)
                            ->where('store_id', $v['start_store_id'])
                            ->update($stockData);
                    }

                }
            }

            Allot::where('id', $req_data['id'])->update([
                'is_del' => 2,
                'del_at' => time(),
            ]);

            AllotInfolist::where('p_id', $req_data['id'])->update([
                'is_del' => 2,
                'del_at' => time(),
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '删除失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }

    /**
     * 审核成功
     */
    public function doauditsuccess(Request $request)
    {
        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);


        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = (int)$accountinfo['store_ids'];


        // 待操作的明细
        if (count($goods_category_ids) > 0) {
            $infolist = AllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = AllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = AllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();
            }
        }

        $allot = Allot::query()
            ->where(['cp_id' => $cp_id])
            ->where('id', $p_id)
            ->first();

        if (empty($infolist) || empty($allot)) {
            return response()->json(['code' => '001', 'msg' => '暂无审核数据']);
        }
        $allot = $allot->toArray();

        if ($store_id>0&&$allot['target_store_id'] != $store_id) {
            return response()->json(['code' => '001', 'msg' => '只有目的门店店长和管理员才能审核']);
        }


        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                // 更新明细
                AllotInfolist::where(['id' => $id, 'cp_id' => $cp_id])
                    ->update(['audit_status' => 2, 'audit_success_count' => $info['count'], 'audit_at' => time()]);
                Stock::query()->where('id', $info['stock_id'])->update(['stock_status' => 3]);

                //调拨后B店+数据
                unset($info['id'], $info['store_id'], $info['create_account_id'], $info['create_account_real_name'], $info['create_at'], $info['update_account_id'], $info['update_account_real_name'], $info['update_at']);

                $info['store_id'] = $info['target_store_id'];
                $info['create_account_id'] = $accountinfo['id'];
                $info['create_account_real_name'] = $accountinfo['real_name'];
                $info['create_at'] = time();
                $info['goods_category_id'] = $info['target_category_id'];

                Stock::query()->create($info);
                // 调拨单审核成功数
                Allot::query()
                    ->where(['id' => $info['p_id'], 'cp_id' => $cp_id])
                    ->increment('audit_success_count', $info['count'], ['audit_status' => 2]);

                //日志
                Log::query()->create([
                    'cp_id' => $cp_id,
                    'store_id' => $info['store_id'],
                    'start_store_id' => $info['start_store_id'],
                    'target_store_id' => $info['target_store_id'],
                    'order_sncode' => $info['order_sncode'],
                    'goods_category_id' => $info['goods_category_id'],
                    'piece_weight' => $info['piece_weight'],
                    'stock_type' => $info['stock_type'],
                    'count' => $info['count'],
                    'cf_no' => $info['cf_no'],
                    'log_type' => 3,
                    'create_at' => time(),
                ]);
            }

            // 检查是否全部审核完成
            $this->saveAllotStatus($cp_id, $p_id);

            DB::commit();
            return response()->json(['code' => '000', 'msg' => '审核成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }

    }

    /**
     * 批量审核成功
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function doauditsuccessmore(Request $request)
    {
        $p_ids = $request->p_ids;
        $p_ids = is_array($p_ids) ? $p_ids : (is_array(json_decode($p_ids, true)) ? json_decode($p_ids, true) : []);


        if (count($p_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = (int)$accountinfo['store_ids'];
        // 待操作的明细
        $infolist = AllotInfolist::where(['cp_id' => $cp_id, 'audit_status' => 1])
            ->whereIn('p_id', $p_ids)->get()->toArray();

        $allot = Allot::query()
            ->where(['cp_id' => $cp_id])
            ->whereIn('id', $p_ids)
            ->get()
            ->toArray();

        if (empty($infolist) || empty($allot)) {
            return response()->json(['code' => '001', 'msg' => '暂无审核数据']);
        }

        $target_store_ids = array_column($allot, 'target_store_id');
        if ($store_id>0&&!in_array($store_id, $target_store_ids)) {
            return response()->json(['code' => '001', 'msg' => '只有目的门店才能审核']);
        }


        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                // 更新明细
                AllotInfolist::where(['id' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 2, 'audit_success_count' => $info['count'], 'audit_at' => time()]);

                Stock::where('id', $info['stock_id'])->update(['stock_status' => 3, 'audit_status' => 2]);

                //调拨后B店+数据
                unset($info['id'], $info['store_id'], $info['create_account_id'], $info['create_account_real_name'], $info['create_at'], $info['update_account_id'], $info['update_account_real_name'], $info['update_at']);
                $info['store_id'] = $info['target_store_id'];
                $info['create_account_id'] = $accountinfo['id'];
                $info['create_account_real_name'] = $accountinfo['real_name'];
                $info['create_at'] = time();
                // 明细审核状态
                $info['goods_category_id'] = $info['target_category_id'];
                Stock::query()->create($info);
                // 调拨单审核成功数
                Allot::where(['id' => $info['p_id'], 'cp_id' => $cp_id])->increment('audit_success_count', $info['count'], ['audit_status' => 2]);

                //日志
                Log::create([
                    'cp_id' => $cp_id,
                    'store_id' => $info['store_id'],
                    'start_store_id' => $info['start_store_id'],
                    'target_store_id' => $info['target_store_id'],
                    'order_sncode' => $info['order_sncode'],
                    'goods_category_id' => $info['goods_category_id'],
                    'piece_weight' => $info['piece_weight'],
                    'stock_type' => $info['stock_type'],
                    'count' => $info['count'],
                    'cf_no' => $info['cf_no'],
                    'log_type' => 3,
                    'create_at' => time(),
                ]);
            }


            // 检查是否全部审核完成

            $this->saveAllotStatus($cp_id, $p_ids);

            DB::commit();
            return response()->json(['code' => '000', 'msg' => '审核成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }

    }

    /**
     * 审核取消
     */
    public function doauditcancel(Request $request)
    {

        $p_id = $request->p_id;
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $goods_style_ids = $request->goods_style_ids;
        $goods_style_ids = is_array($goods_style_ids) ? $ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $goods_category_ids = $request->goods_category_ids;
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        if (count($ids) == 0 && count($goods_style_ids) == 0 && count($goods_category_ids) == 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = (int)$accountinfo['store_ids'];

        if (count($goods_category_ids) > 0) {
            $infolist = AllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('goods_category_id', $goods_category_ids)->get()->toArray();
        } else {
            if (count($goods_style_ids) > 0) {
                $infolist = AllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('goods_style_id', $goods_style_ids)->get()->toArray();
            } else {
                $infolist = AllotInfolist::where(['p_id' => $p_id, 'cp_id' => $cp_id, 'audit_status' => 1])->whereIn('id', $ids)->get()->toArray();
            }
        }

        $allot = Allot::query()
            ->where(['cp_id' => $cp_id])
            ->where('id', $p_id)
            ->first();
        if (empty($infolist) || empty($allot)) {
            return response()->json(['code' => '001', 'msg' => '审核数据不存在']);
        }
        $allot = $allot->toArray();


        if ($store_id>0&&$store_id != $allot['target_store_id']) {
            return response()->json(['code' => '001', 'msg' => '只有目的门店才能取消']);
        }

        $stockIds = array_column($infolist, 'stock_id');
        $stockList = Stock::query()
            ->where(['cp_id' => $cp_id])
            ->whereIn('id', $stockIds)
            ->get()
            ->pluck(null, 'id')
            ->toArray();


        DB::beginTransaction();
        try {
            foreach ($infolist as $info) {
                $id = $info['id'];
                AllotInfolist::where(['id' => $id, 'cp_id' => $cp_id])->update(['audit_status' => 3, 'audit_failed_count' => $info['count'], 'audit_at' => time()]);
                // 审核取消数
                Allot::where(['id' => $info['p_id'], 'cp_id' => $cp_id])->increment('audit_failed_count', $info['count'], ['audit_status' => 3]);

                // 取消退回库存
                $stock = $stockList[$info['stock_id']] ?? [];

                if (!empty($stock)) {
                    $stockData = $this->checkBCstock($stock, $info, true);
                    $stockData['stock_status'] = 1;
                    $stockData['update_at'] = time();
                    $stockData['audit_status'] = 3;
                    Stock::query()
                        ->where('id', $info['stock_id'])
                        ->where('cp_id', $cp_id)
                        ->where('store_id', $info['start_store_id'])
                        ->update($stockData);
                }


                //日志
                Log::create([
                    'cp_id' => $cp_id,
                    'store_id' => $info['store_id'],
                    'start_store_id' => $info['start_store_id'],
                    'target_store_id' => $info['target_store_id'],
                    'order_sncode' => $info['order_sncode'],
                    'goods_category_id' => $info['goods_category_id'],
                    'piece_weight' => $info['piece_weight'],
                    'stock_type' => $info['stock_type'],
                    'count' => $info['count'],
                    'cf_no' => $info['cf_no'],
                    'log_type' => 4,
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                ]);

                $this->saveAllotStatus($cp_id, $p_id);

            }
            DB::commit();
            return response()->json(['code' => '000', 'msg' => '审核取消成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }

    }


    /**
     * 计算
     * @param $stock
     * @param $allot
     * @param $isAdd
     * @param $is_new_stock
     * @return array
     */
    protected function checkBCstock($stock, $allot, $isAdd = true,$is_new_stock=0)
    {
        $stockData = [];
        $count =$allot['count']??0;
        $netglod_weight_new = $stock['netglod_weight_new'] > 0 ? (bcdiv($stock['netglod_weight_new'], $stock['count'], 4)) : 0;
        $netglod_weight = $stock['netglod_weight'] > 0 ? (bcdiv($stock['netglod_weight'], $stock['count'], 4)) : 0;
        $piece_weight_new = $stock['piece_weight_new'] > 0 ? (bcdiv($stock['piece_weight_new'], $stock['count'], 4)) : 0;
        $piece_weight = $stock['piece_weight'] > 0 ? (bcdiv($stock['piece_weight'], $stock['count'], 4)) : 0;
        $old_recovery_price = $stock['old_recovery_price'] > 0 ? (bcdiv($stock['old_recovery_price'], $stock['count'], 2)) : 0;
        $exchange_amount = $stock['exchange_amount'] > 0 ? (bcdiv($stock['exchange_amount'], $stock['count'], 2)) : 0;
        $valuations = $stock['valuations'] > 0 ? (bcdiv($stock['valuations'], $stock['piece_weight'], 2)) : 0;

        if($is_new_stock==0){

            if ($isAdd == true) {
                if($piece_weight_new == 0 || $piece_weight == 0)
                {
                    //只有删除和取消审核的场景涉及
                    //旧料老的库存清空了，所以单重计算有问题需要直接取调拨单的单重
                    $piece_weight_new = $allot['piece_weight_new'] > 0 ? (bcdiv($allot['piece_weight_new'], $allot['count'], 4)) : 0;
                    $piece_weight = $allot['piece_weight'] > 0 ? (bcdiv($allot['piece_weight'], $allot['count'], 4)) : 0;
                }

                $stockData['count'] = $stock['count'] + $count;
                // 计算累加的总成本
                $is_gram =GoodsCategory::query()
                    ->where(['is_del'=>1,'id'=>$stock['goods_category_id']])
                    ->value('is_gram')??0;
                $incr['total_netglod_weight'] = $netglod_weight*$count;
                $incr['total_cost_fee'] = $allot['netglod_weight'];
                list($total_cost_fee,$costglod_price,$piececost_fee) =(new Goods())->incrTotalCost($stock,$incr,$is_gram);

                $stockData['total_cost_fee'] = $total_cost_fee;
                $stockData['costglod_price'] = $costglod_price;
                $stockData['piececost_fee'] = $piececost_fee;
            } else {
                $stockData['count'] = $stock['count'] - $count;
                $deduction['total_netglod_weight'] = $netglod_weight*$count;
                // 计算扣减的总成本
                list($deduct_total_cost_fee,$remaining_cost_fee)  =(new Goods())->deductTotalCost($stock,$deduction);
                $stockData['deduct_total_cost_fee'] = $deduct_total_cost_fee;
                $stockData['remaining_cost_fee'] = $remaining_cost_fee;
            }
        }else{
            $stockData['count'] = $count;
        }
        $stockData['netglod_weight'] = bcmul($netglod_weight, $stockData['count'], 3);
        $stockData['netglod_weight_new'] = bcmul($netglod_weight_new, $stockData['count'], 3);
        $stockData['piece_weight'] = bcmul($piece_weight, $stockData['count'], 3);
        $stockData['piece_weight_new'] = bcmul($piece_weight_new, $stockData['count'], 3);

        $stockData['old_recovery_price'] = round(bcmul($old_recovery_price, $stockData['count']));
        $stockData['exchange_amount'] = round(bcmul($exchange_amount, $stockData['count']));
        $stockData['valuations'] = round(bcmul($valuations, $stockData['piece_weight']));
        return $stockData;
    }


    /**更新张主订单状态
     * @param $cp_id
     * @param $p_id
     * @return true
     */
    protected function saveAllotStatus($cp_id, $p_id)
    {
        $p_ids = is_array($p_id) ? $p_id : [$p_id];

        $count = AllotInfolist::query()
            ->where(['cp_id' => $cp_id, 'audit_status' => 1])
            ->whereIn('p_id', $p_ids)
            ->count();
        if ($count == 0) {
            Allot::query()
                ->where(['cp_id' => $cp_id])
                ->whereIn('id', $p_ids)
                ->update(['audit_status' => 3]);
        }

        return true;
    }
}
